from GBDTModel import GBDTModel
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from pandas import DataFrame
from scipy.interpolate import make_interp_spline

sns.set()


def main():
    dataset = pd.read_excel('../../data/newData.xlsx')
    # 要分析的数据
    X = dataset.iloc[5:, 1:360].values

    print("======原始数据的形状========")
    print(np.array(X).shape)
    # print(X)

    # 转置
    X_index = [[row[i] for row in X] for i in range(len(X[0]))]
    X_index = np.array(X_index)

    # 输入数据
    x = x = np.array(X_index)
    print(np.array(x).shape)

    x = np.array(x)
    x = x[:, 50:300]
    print("输入数据:%s" % x)
    print(np.array(x).shape)

    # 原始机测、手测数据 q值
    mmv = pd.read_excel('../../excelData/q_value.xlsx')
    print("======原始机测、手测数据的形状========")
    print(np.array(mmv).shape)
    # print(mmv)
    second_machine_value = mmv.iloc[3, 1:28].values
    second_manual_value = mmv.iloc[4, 1:28].values
    # 机测q值
    second_machine_value = np.array(second_machine_value)
    second_machine_value=four_time_nums(second_machine_value)
    second_machine_value = np.array(second_machine_value)
    # 手测q值
    second_manual_value = np.array(second_manual_value)
    second_manual_value=four_time_nums(second_manual_value)
    second_manual_value = np.array(second_manual_value)

    # 求出预测q
    model = GBDTModel
    x = np.array(x)
    print("============模型预测=============")
    q_predict = get_q_layer_high(x)
    print("q预测结果：%s" % (q_predict))

    predict = q_predict
    # # 预测值处理
    # predict = []
    # for i in range(int(len(q_predict) / 4)):
    #     tmp = q_predict[4 * i:4 * i + 4]
    #     # print(tmp)
    #     max = 0
    #     for j in range(4):
    #         if tmp[j] > max:
    #             max = tmp[j]
    #     predict.append(max)
    #
    # print("predict:%s" % (predict))
    # print(np.array(predict).shape)
    # 保存q值

    df = DataFrame(predict)
    df.to_excel('../../excelData/q150-300_predict_location.xlsx')

    # second_machine_value = [[second_machine_value[i] for row in second_machine_value] for i in
    #                        range(len(second_machine_value))]
    print(np.array(second_machine_value).shape)
    print("second_machine_value:%s" % (second_machine_value))
    # 水平线
    leavel = [0] * 27 * 4
    # 机测与手测误差
    # machine_bias = second_machine_value - second_manual_value
    machine_bias = abs(second_machine_value - second_manual_value)
    # 预测与手测误差
    # predict_bias = predict - second_manual_value
    predict_bias = abs(predict - second_manual_value)
    print("predict_bias:%s" % (predict_bias))
    print("machine_bias:%s" % (machine_bias))
    # 预测、机测、手测 画图
    # 解决中文显示问题
    plt.rcParams['font.sans-serif'] = ['KaiTi']  # 指定默认字体
    plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题
    plt.figure(figsize=(15, 15))
    # 图一：每年上映电影的总收入
    ax = plt.subplot(111)
    # 设置x轴 范围
    ax.set_xlim(0, 108)
    # 设置x轴 主刻度，（次刻度设置minor=True）
    ax.set_xticks(np.arange(0, 108, 1), minor=False)
    # 画图
    xx = np.linspace(1, 108, 108)
    ax.plot(xx, machine_bias, linestyle='--', marker='o', markersize=5, color='green')
    ax.plot(xx, leavel, linestyle='--', marker='o', markersize=5, color='#900302')
    ax.plot(xx, predict_bias, linestyle='--', marker='o', markersize=5, color='#000000')
    plt.legend(('machine_bias', 'leavel', 'predict_bias'), loc='upper right')
    # 增加竖线
    # ax.axvline(x=y_manual[i], color='#d46061', linewidth=1)
    # ax.axvline(x=k_manual[i], color='#000000', linewidth=1)
    # ax.axvline(x=q_manual[i], color='#F9F900', linewidth=1)
    # ax.set_title("空气层和清液层分界面机测与本模型预测绝对值误差")
    ax.set_title("空气层和清液层分界面机测与本模型预测绝对值误差")
    ax.set_ylabel("高度误差")
    f = plt.gcf()  # 获取当前图像
    plt.show()
    f.savefig('predict_qq_abs.png')


# 数组放大四倍
def four_time_nums(num):
    length = len(num)
    result=[]
    for i in num:
        for j in range(4):
            result.append(i)
    return result


# 获取q层高度
# input: 360*n  n组数据
# return  n组数据对应的第三层高度
def get_q_layer_high(input):
    length=len(input[0])
    # 模型
    model = GBDTModel
    print("==========X_index=============")
    print(np.array(input).shape[0])
    q_layer_high_num = np.array(range(np.array(input).shape[0]), dtype=float)
    for i in range(np.array(input).shape[0]):
        # 处理空值
        for j in range(length):
            if np.isnan(input[i][j]):
                input[i][j] = 0
        res = model.predict(model, input[i], name, index)
        print(f"{i + 1}预测值为：{res} ")

        q_layer_high_num[i] = res

    print("==========three_layer_high_num=============")
    print(np.array(q_layer_high_num).shape)
    # print(three_layer_high_num)
    return q_layer_high_num


index = 5
name = "q_"
num_of_index = 1
if __name__ == "__main__":
    main()
